package com.wjm.blog.common.util.tree;


import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Tree解析工具类
 *
 * @author Administrator
 * @version 1.0
 */
public class TreeUtil {

    public static <T extends TreeNode> List<T> buildTree(List<T> trees) {
        if (!CollectionUtils.isEmpty(trees)) {
            //建树逻辑
            for (T tree : trees) {
                //递归查询出资源子节点信息
                recursionChildren(tree, trees);
            }
            //双层循环去重
            List<T> ids = new ArrayList<>();
            for (T tree : trees) {
                for (T tre : trees) {
                    if (tree.getId().equals(tre.getParentId())) {
                        ids.add(tre);
                    }
                }
            }
            trees.removeAll(ids);
        }
        //对集合各级排序
        sort(trees);
        return trees;
    }

    public static <T extends TreeNode> T recursionChildren(T treeModel, List<T> list) {
        //如果一个节点的父id等于参数节点的id，则把这个节点写入参数节点的子节点list
        List<T> children = new ArrayList<>();
        List<T> param = new ArrayList<>();
        for (T listVo : list) {
            if (listVo.getParentId().equals(treeModel.getId())) {
                children.add(listVo);
                T grandChild = recursionChildren(listVo, list);
                param.add(grandChild);
            }
        }

        //最终返回传进来的带有所有子节点的参数节点
        treeModel.setChildList(param);
        return treeModel;
    }


    private static  <T extends TreeNode> void sort(List<T> trees) {
        Collections.sort(trees, (o1, o2) -> {
            if (o1.getResourceSort() != null && o2.getResourceSort() != null) {

                return o1.getResourceSort() - o2.getResourceSort();
            }
            return 0;
        });
        for (T tree : trees) {
            if (!com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(tree.getChildList())) {
                sort(tree.getChildList());
            }
        }
    }
}
